import api from './request'

// 跨域测试工具
export const corsTest = {
  // 测试基础 API 连接
  async testApiConnection() {
    try {
      const response = await api.get('/test/connection')
      console.log('✅ API 连接测试成功:', response)
      return { success: true, data: response }
    } catch (error) {
      console.error('❌ API 连接测试失败:', error)
      return { success: false, error: error.message }
    }
  },

  // 测试文件上传
  async testFileUpload(file) {
    try {
      const response = await api.upload('/upload/test', file, (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        console.log(`📤 上传进度: ${percentCompleted}%`)
      })
      console.log('✅ 文件上传测试成功:', response)
      return { success: true, data: response }
    } catch (error) {
      console.error('❌ 文件上传测试失败:', error)
      return { success: false, error: error.message }
    }
  },

  // 测试 WebSocket 连接
  testWebSocketConnection() {
    return new Promise((resolve) => {
      const ws = new WebSocket('ws://localhost:8080/ws')
      
      ws.onopen = () => {
        console.log('✅ WebSocket 连接成功')
        ws.close()
        resolve({ success: true })
      }
      
      ws.onerror = (error) => {
        console.error('❌ WebSocket 连接失败:', error)
        resolve({ success: false, error: 'WebSocket 连接失败' })
      }
      
      // 5秒超时
      setTimeout(() => {
        if (ws.readyState !== WebSocket.OPEN) {
          ws.close()
          resolve({ success: false, error: 'WebSocket 连接超时' })
        }
      }, 5000)
    })
  },

  // 运行所有测试
  async runAllTests() {
    console.log('🚀 开始跨域测试...')
    
    const results = {
      api: await this.testApiConnection(),
      upload: await this.testFileUpload(new File(['test'], 'test.txt')),
      websocket: await this.testWebSocketConnection()
    }
    
    console.log('📊 跨域测试结果:', results)
    
    const allPassed = Object.values(results).every(result => result.success)
    if (allPassed) {
      console.log('🎉 所有跨域测试通过!')
    } else {
      console.warn('⚠️ 部分跨域测试失败，请检查配置')
    }
    
    return results
  }
}

// 导出测试函数
export default corsTest 